// pages/uploadImg.js
var api = require('./../../config/api.js');
var app = getApp();
var util = require('./../../utils/util.js');


// 初始化七牛相关参数
function initQiniu() {
  var options = {
    region: 'SCN', // 华南区
    domain: 'http://pdg4eya6u.bkt.clouddn.com',
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    groupList: [],
    id: "",
    isUser: false,
    isView: false,
    uId: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({id: options.id})
    if (options.isUser == 1 ){
      this.setData({isUser: true})
    }
    console.log('isUser:')
    console.log(this.data.isUser)
    if (options.isView == 1 ){
      this.setData({isView: true})
    }
    console.log('isView:')
    console.log(this.data.isView)

    if (options.uId){
      this.setData({uId: options.uId})
    }else{
      this.setData({uId: app.globalData.userInfo.uCode})
    }
    this.loadData();
  },

  loadData: function(){
    if (app.globalData.userInfo){
      console.log(app.globalData.userInfo)
      var postData = {}
      postData.uId = this.data.uId
      if (this.data.isUser){
        postData.belongId = this.data.id + "_user"
      }else{
        postData.belongId = this.data.id
      }
      
      var that = this;
      util.myRequest(api.GetPhotoGroupList, postData, function (data) {
        that.setData({groupList: data.data})
      });
    }else{
      var that = this;
      setTimeout(function(){
        that.loadData();
      }, 200);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  addNewPhotos: function(){
    var e = {currentTarget: {dataset:{index: this.data.groupList.length}}}
    this.uploadPhotos(e)
  },

  /**
   * 上传图片
   */
  uploadPhotos: function (e) {
    var index = e.currentTarget.dataset.index;
    const that = this;

    var maxCount = 8
    console.log(that.data.groupList)
    if (that.data.groupList.length > index){
      maxCount = maxCount - that.data.groupList[index].picture_url.length
    }
    if (maxCount == 0){
      wx.showToast({
        title: '最多上传8张图',
        duration: 2000
      })
      return;
    }

    wx.chooseImage({
      count: maxCount,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        initQiniu();

        that.upLoadImage(tempFilePaths, 0, [], function(photoUrlArray) {
          var newGroupList = that.data.groupList;
          if (that.data.groupList.length <= index){
            newGroupList[index] = {"picture_url": [], "pgDescribe": ""}
          }
          newGroupList[index].picture_url = newGroupList[index].picture_url.concat(photoUrlArray)
          that.setData({groupList: newGroupList})
        });
      }
    })
  },

  // 上传图片
  upLoadImage: function(photos, index, photoUrl, callback) {

    if (photos.length == index) {
      wx.hideLoading();
      callback(photoUrl);
      return;
    }

    var that = this;

    var url = api.QiniuTokenInfo + '/' + app.globalData.userInfo.token;
    util.myRequest(url, false, function(data) {
      //////////////////////////
      var filePath = photos[index];

      setTimeout(function(){
        wx.hideLoading();
        wx.showLoading({
          title: '正在上传' + (index + 1) + '/' + photos.length,
        });
      }, 0);

      // 交给七牛上传
      qiniuUploader.upload(filePath, (res) => {
          wx.hideLoading();
          console.log('upload callback')
          console.log(res)
          // photoUrl.push(res.imageURL);
          photoUrl.push(data.data.url);
          
          that.upLoadImage(photos, index + 1, photoUrl, callback)
          // wx.showToast({
          //   title: '第' + (i + 1) + '张完成上传',
          //   icon: 'loading',
          //   duration: 1000
          // })
        }, (error) => {
          wx.hideLoading();
          console.error('error: ' + JSON.stringify(error));
        }, {
          uptoken: data.data.token,
          key: data.data.name,
          region: 'SCN', // 华南区
        }, // 可以使用上述参数，或者使用 null 作为参数占位符
        (progress) => {
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
        }, cancelTask => that.setData({
          cancelTask
        })
      );
      //////////////////////////
    });
  },

  deleteImg: function(e){
    console.log(e)
    var groupIdx = e.currentTarget.dataset.groupidx;
    var picIdx = e.currentTarget.dataset.picidx;

    var imgs = this.data.groupList[groupIdx].picture_url
    imgs.splice(picIdx, 1);
    var newGroupList = this.data.groupList
    newGroupList[groupIdx].picture_url = imgs
    this.setData({
      groupList: newGroupList
    });
  },

  handelInput: function(e){
    console.log(e)
    var groupIdx = e.currentTarget.dataset.groupidx;
    var newGroupList = this.data.groupList
    newGroupList[groupIdx].pgDescribe = e.detail.value

    this.setData({
      groupList: newGroupList
    });
  },

  save: function(){
    var dataStr = JSON.stringify(this.data.groupList)
    console.log(dataStr)
    var postData = {}
    postData.groupList = dataStr
    postData.uId = app.globalData.userInfo.uCode
    if (this.data.isUser){
      postData.belongId = this.data.id + "_user"
    }else{
      postData.belongId = this.data.id
    }

    util.myRequest(api.ResetPhotos, postData, function (data) {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
      setTimeout(function(){
        wx.navigateBack()
      }, 1000)
    });
  },

  previewImg: function(e){
    console.log(e)
    wx.previewImage({
      current: this.data.groupList[e.currentTarget.dataset.groupidx].picture_url[e.currentTarget.dataset.picidx], // 当前显示图片的http链接
      urls: this.data.groupList[e.currentTarget.dataset.groupidx].picture_url // 需要预览的图片http链接列表
  })
  }
})